﻿using System;
using System.Collections.Generic;
using System.Linq;
using ETL.Business.Models;
using ETL.Common.Logging;
using ETL.DataAccess;
using ETL.Entity;

namespace ETL.Business.Handlers.ProjectUserHandler
{
    public class GetActiveUsers
    {
        private readonly ProjectUserRepository _projectUserRepository;
        private readonly ProjectResourceInstanceRepository _projectResourceInstanceRepository;

        public GetActiveUsers()
        {
            _projectUserRepository = new ProjectUserRepository();
            _projectResourceInstanceRepository = new ProjectResourceInstanceRepository();
        }
        public GetActiveUsers(ProjectUserRepository projectUserRepository, ProjectResourceInstanceRepository projectResourceInstanceRepository)
        {
            _projectUserRepository = projectUserRepository;
            _projectResourceInstanceRepository = projectResourceInstanceRepository;
        }

        public virtual IEnumerable<ProjectUserModel> Execute()
        {
            IEnumerable<ProjectUserModel> projectEngineerModel = null;
            
            try
            {
                // try to get from db
                IEnumerable<APP_USERS> allUsers = _projectUserRepository.GetAllAppUser();
                IEnumerable<RESOURCE_INSTANCES> allActiveUsers =
                    _projectResourceInstanceRepository.GetAllResourceInstances();

                // parse to business model
                if(allUsers != null && allActiveUsers != null)
                {
                    var tmp =   from user in allUsers
                                join activeUser in allActiveUsers
                                on user.DSE_ID.ToUpper() equals activeUser.RESOURCE_NAME.ToUpper()
                                select user;

                    projectEngineerModel = from s in tmp.Distinct() select new ProjectUserModel(s);

                }

                return projectEngineerModel;
            }
            catch (Exception ex)
            {
                LogService.Service.Debug(ex);
                return null;
            }
        }

        public virtual List<ProjectUserModel> ExecuteToList()
        {
            try
            {
                IEnumerable<ProjectUserModel> projectEngineerModel = Execute();
                if (projectEngineerModel != null && projectEngineerModel.Count() > 0)
                    return projectEngineerModel.ToList();
                else
                    return new List<ProjectUserModel>();
            }
            catch (Exception ex)
            {
                LogService.Service.Debug(ex);
                return new List<ProjectUserModel>();
            }
        }
    }
}